<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG Example</title>
</head>
<style>
    #canvasBackground {
        margin: 50px;
        background: rgba(0, 0, 0, 0.1);
    }

    .tools {
        position: fixed;
        top: 10px;
        right: 20px;
    }
</style>

<body>
    <svg id="canvasBackground" width="600" height="400"></svg>
    <div class="tools">
        <button id="createRectBtn">创建</button>
        <select name="" id="select">
            <option value="25">25</option>
            <option value="50">50</option>
            <option value="75">75</option>
            <option value="100">100</option>
            <option value="150">150</option>
            <option value="200">200</option>
        </select>
    </div>
    <script>
        let ratioPercentage = 0;
        const dpmm = 96 / 25.4;
        const bgSvg = document.getElementById('canvasBackground');
        const selectDom = document.getElementById('select');
        const createRectBtn = document.getElementById("createRectBtn");

        // 定义变量用于存储鼠标移动时的初始位置
        let isDragging = false;
        let pendingAnimationFrame = false;
        let mouseX, mouseY;

        selectDom.addEventListener("change", (e) => {
            const selectedValue = parseInt(e.target.value); // 获取选择的值
            const currentWidth = parseInt(bgSvg.getAttribute('width')); // 获取当前宽度
            const currentHeight = parseInt(bgSvg.getAttribute('height')); // 获取当前高度

            // 计算新的宽度和高度，这里按比例放大
            const scale = selectedValue / 100;
            const newWidth = currentWidth * scale;
            const newHeight = currentHeight * scale;

            // 更新 bgSvg 的宽度和高度
            bgSvg.setAttribute('width', newWidth);
            bgSvg.setAttribute('height', newHeight);

            // 更新内部矩形的宽度和高度以及位置
            const rect = bgSvg.querySelector('rect');
            const path = bgSvg.querySelector('path');

            if (rect && path) {
                // 计算新的矩形宽度和高度
                const rectWidth = parseInt(rect.getAttribute('width')) * scale;
                const rectHeight = parseInt(rect.getAttribute('height')) * scale;
                rect.setAttribute('width', rectWidth);
                rect.setAttribute('height', rectHeight);

                // 更新路径数据
                const newPathData = `
            M 0,0 L ${25 * scale},0 M 0,0 L 0,${25 * scale}
            M ${rectWidth},0 L ${rectWidth - 25 * scale},0 M ${rectWidth},0 L ${rectWidth},${25 * scale}
            M 0,${rectHeight} L ${25 * scale},${rectHeight} M 0,${rectHeight} L 0,${rectHeight - 25 * scale}
            M ${rectWidth},${rectHeight} L ${rectWidth - 25 * scale},${rectHeight} M ${rectWidth},${rectHeight} L ${rectWidth},${rectHeight - 25 * scale}
        `;
                path.setAttribute('d', newPathData);
            }
        });



        const createSvgConcentrator = function () {
            // 获取原始SVG容器的宽度和高度
            const containerWidth = Number(bgSvg.getAttribute('width'));
            const containerHeight = Number(bgSvg.getAttribute('height'));

            // 计算缩放比例（20分之一）
            const scale = 1 / 5;

            // 计算新的SVG容器的宽度和高度
            const newWidth = containerWidth * scale;
            const newHeight = containerHeight * scale;

            // 计算矩形的宽度和高度（按照13:8的比例）
            const ratio = 13 / 8;
            let rectWidth, rectHeight;
            if (newWidth / newHeight > ratio) {
                rectHeight = newHeight;
                rectWidth = rectHeight * ratio;
            } else {
                rectWidth = newWidth;
                rectHeight = rectWidth / ratio;
            }
            // 创建SVG元素
            const svgContainer = document.createElementNS('http://www.w3.org/2000/svg', "svg");
            svgContainer.setAttribute("width", rectWidth);
            svgContainer.setAttribute("height", rectHeight);
            svgContainer.setAttribute("id", 'svgThicknessConcentrator');
            svgContainer.setAttribute("style", "background: rgba(0,0,0,0.4); cursor: grab;");
            document.body.appendChild(svgContainer); // 将SVG元素添加到页面中

            // 创建一个新的矩形组元素
            const rectGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');

            // 创建一个矩形元素
            const rectangle = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
            rectangle.setAttribute('x', '0');
            rectangle.setAttribute('y', '0');
            rectangle.setAttribute('width', rectWidth);
            rectangle.setAttribute('height', rectHeight);
            rectangle.setAttribute('fill', 'rgba(255,255,255,0.42)'); // 设置填充色

            // 定义路径数据
            const pathData = `
                M 0,0 L 25,0 M 0,0 L 0,25
                M ${rectWidth},0 L ${rectWidth - 25},0 M ${rectWidth},0 L ${rectWidth},25
                M 0,${rectHeight} L 25,${rectHeight} M 0,${rectHeight} L 0,${rectHeight - 25}
                M ${rectWidth},${rectHeight} L ${rectWidth - 25},${rectHeight} M ${rectWidth},${rectHeight} L ${rectWidth},${rectHeight - 25}
            `;

            // 创建路径元素
            const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            path.setAttribute('d', pathData);
            path.setAttribute('stroke', '#FF5C02');
            path.setAttribute('stroke-width', '2');
            path.setAttribute('fill', 'none');

            // 将路径元素添加到矩形组中
            rectGroup.appendChild(rectangle);
            rectGroup.appendChild(path);

            // 将矩形组元素添加到SVG容器中
            svgContainer.appendChild(rectGroup);

            return svgContainer;
        };
        // 定义函数用于处理矩形的移动
        const updateRectPosition = (rect) => {
            return function () {
                // 获取SVG元素的宽度和高度
                let svgWidth = parseInt(bgSvg.getAttribute("width"));
                let svgHeight = parseInt(bgSvg.getAttribute("height"));

                // 获取矩形的大小
                let rectWidth = parseInt(rect.getAttribute("width"));
                let rectHeight = parseInt(rect.getAttribute("height"));

                // 计算鼠标位置相对于SVG的坐标
                let svgRect = bgSvg.getBoundingClientRect();
                let newX = mouseX - svgRect.left - rectWidth / 2;
                let newY = mouseY - svgRect.top - rectHeight / 2;

                // 确保矩形不超出SVG边界
                newX = Math.max(0, Math.min(svgWidth - rectWidth, newX));
                newY = Math.max(0, Math.min(svgHeight - rectHeight, newY));

                // 更新矩形的位置
                rect.setAttribute("x", newX);
                rect.setAttribute("y", newY);

                pendingAnimationFrame = false;

                if (isDragging) {
                    requestAnimationFrame(updateRectPosition(rect));
                }
            };
        }

        const createThicknessSetector = function () {
            const detectionThicknessDomId = 'svgThicknessConcentrator';

            // 检查SVG中是否已经存在矩形
            if (bgSvg.getElementById("svg-thickness-concentrator")) {
                return;
            }

            const detectionThicknessDom = createSvgConcentrator();
            const eventListeners = [];
            const addEventListenerWithTracking = (element, event, handler) => {
                element.addEventListener(event, handler);
                eventListeners.push({ element, event, handler });
            };

            // 鼠标事件处理函数
            const handleMouseMove = (event) => {
                if (isDragging) {
                    mouseX = event.clientX;
                    mouseY = event.clientY;
                    if (!pendingAnimationFrame) {
                        pendingAnimationFrame = true;
                        requestAnimationFrame(updateRectPosition(detectionThicknessDom));
                    }
                }
            };

            // 添加鼠标移入SVG事件监听器
            addEventListenerWithTracking(bgSvg, "mouseenter", function (event) {
                isDragging = true;
                mouseX = event.clientX;
                mouseY = event.clientY;
                requestAnimationFrame(updateRectPosition(detectionThicknessDom));
            });

            // 添加鼠标移出SVG事件监听器
            addEventListenerWithTracking(bgSvg, "mouseleave", function (event) {
                isDragging = false;
            });

            // 添加鼠标移动事件监听器
            addEventListenerWithTracking(bgSvg, "mousemove", handleMouseMove);



            // 添加矩形点击事件监听器
            addEventListenerWithTracking(detectionThicknessDom, "click", function () {
                const detectionThicknessDomInfo = {
                    x: detectionThicknessDom.getAttribute("x"),
                    y: detectionThicknessDom.getAttribute("y"),
                    width: detectionThicknessDom.getAttribute("width"),
                    height: detectionThicknessDom.getAttribute("height"),
                };
                console.log(detectionThicknessDomInfo);
                // thicknessDetectionEventEmitter.emit('UPDATE_THICKNESS_COORDINATE', detectionThicknessDomInfo);

                // 移除所有事件监听器
                eventListeners.forEach(({ element, event, handler }) => element.removeEventListener(event, handler));

                // 销毁矩形
                detectionThicknessDom.parentNode.removeChild(detectionThicknessDom);
            });
            // 添加矩形右键点击事件监听器
            addEventListenerWithTracking(detectionThicknessDom, "contextmenu", function (event) {
                event.preventDefault(); // 阻止默认右键菜单

                // 移除所有事件监听器
                eventListeners.forEach(({ element, event, handler }) => element.removeEventListener(event, handler));

                // 销毁矩形
                detectionThicknessDom.parentNode.removeChild(detectionThicknessDom);
            });

            bgSvg.appendChild(detectionThicknessDom);
        }
        createRectBtn.addEventListener('click', function () {
            createThicknessSetector();
        })
    </script>
</body>

</html>